/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Logger;

/**
 *
 * @author selkhateeb
 */
public class Jar {

    private static Logger logger = Logger.global;

    /**
     * Extracts a single file from the jar to the specified destination.
     * @param jarFileName
     * @param sourceFile
     * @param destinationDirectory
     * @throws java.io.IOException
     */
    public static void ExtractSingleFile(File JARFile,
                                         String sourceFile,
                                         String destinationDirectory)
            throws IOException {
        JarFile jarFile = new JarFile(JARFile);
        ExtractSingleFile(jarFile, sourceFile, destinationDirectory);

    }

    public static void ExtractSingleFile(String jarFileName,
                                         String sourceFile,
                                         String destinationDirectory)
            throws IOException {
        File jarFile = new File(jarFileName);
        ExtractSingleFile(jarFile, sourceFile, destinationDirectory);
    }

    public static void ExtractFileList(JarFile jarFile, Collection<String> sourceFilesList, String destinationDirectory) throws IOException {
        for (String file : sourceFilesList) {
            ExtractSingleFile(jarFile, file, destinationDirectory);
        }
    }

    public static void ExtractFileList(File jarFile, Collection<String> sourceFilesList, String destinationDirectory) throws IOException {
        JarFile jf = new JarFile(jarFile);
        ExtractFileList(jf, sourceFilesList, destinationDirectory);
    }

    public static void ExtractFileList(String jarFileName, Collection<String> sourceFilesList, String destinationDirectory) throws IOException {
        File jf = new File(jarFileName);
        ExtractFileList(jf, sourceFilesList, destinationDirectory);
    }

    public static void ExtractSingleFile(JarFile jarFile, String sourceFile,
                                         String destinationDirectory) throws IOException {
        JarEntry jarEntry = jarFile.getJarEntry(sourceFile);
//        File destination = new File(destinationDirectory, jarEntry.getName().substring(sourceFile.lastIndexOf(File.separatorChar)));
        File destination = new File(destinationDirectory, jarEntry.getName().substring(sourceFile.lastIndexOf(File.separatorChar)));

//        if (destination.isDirectory() || destination.getAbsolutePath().endsWith(File.separator)) {
//            return; //TODO: maybe we should tell the user
//        }
        logger.info("Extracting: " + destination);
        File parentDirectories = new File(destination.getParent());
        if (!parentDirectories.exists()) {
            logger.info("Creating directories: " + destination.getParent());
            parentDirectories.mkdirs();
        }

        InputStream in = jarFile.getInputStream(jarEntry);

        OutputStream out = new FileOutputStream(destination);

        FileUtility.Copy(in, out);

    }

    public static void ExtractDirectory(File file, String sourceDirectory,
                                        String destinationDirectory) throws IOException {

        logger.info("Absulute Path for Jar: " + file.getAbsolutePath());
        logger.info("SourceDirectory: " + sourceDirectory);
        logger.info("destinationDirectory: " + destinationDirectory);

        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> e = jarFile.entries();
        while (e.hasMoreElements()) {
            JarEntry entry = e.nextElement();
//            logger.info(entry.getName());
            if (entry.getName().startsWith(sourceDirectory)) {
                if (entry.getName().endsWith(File.separator)) {
                    continue; //Nothing to do
                }
                ExtractSingleFile(jarFile, entry.getName(), destinationDirectory);
            }
        }

    }

    public static void CopyFilesToLocation(File jarFile,
                                                     String srcDir,
                                                     String destDir)
            throws IOException {

        logger.finest("CopyProjectTemplateFiles");
        JarFile jar = new JarFile(jarFile);
        logger.info("Jar :" + jar.getName());
        Enumeration iterator = jar.entries();

        int fileCounter = 0;
        while (iterator.hasMoreElements()) {
            JarEntry je = (JarEntry) iterator.nextElement();
            if (je.getName().startsWith(srcDir)) {
                fileCounter++;
                String destinationPrefixRemoved =
                        je.getName().
                        substring(srcDir.length());

                File dist = new File(destDir,
                                     destinationPrefixRemoved);
                if (je.isDirectory()) {
                    logger.info("Creating directory: " +
                                dist.getName());
                    dist.mkdirs();
                }
                else {
                    logger.info("Creating file: " +
                                dist.getName());
                    InputStream in =
                            new BufferedInputStream(jar.getInputStream(je));

                    OutputStream out =
                            new BufferedOutputStream(
                            new FileOutputStream(dist));

                    FileUtility.Copy(in, out);

                }
            }
        }
    }
}
